package com.whalefin.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whalefin.domain.LeaveMessage;
import com.whalefin.domain.Reply;
import com.whalefin.domain.User;
import com.whalefin.persistence.LeaveMessageMapper;
import com.whalefin.persistence.ReplyMapper;
import com.whalefin.persistence.UserMapper;
import com.whalefin.persistence.tools.PaginationUtils;
import com.whalefin.service.tools.ApplicationParams;
import com.whalefin.service.tools.BooleanResult;
import com.whalefin.service.tools.UploadTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class LeaveMessageService {

    @Autowired
    private LeaveMessageMapper leaveMessageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReplyMapper replyMapper;

    /**
     * 发布留言
     * @param msg_title 发布标题
     * @param msg_content 发布内容
     * @param userId 发布人id
     * @param msg_pic 图片
     */
    @RequestMapping(method = RequestMethod.POST ,value = "/addLeaveMsg")
    public @ResponseBody
    BooleanResult addLeaveMsg(@RequestParam String msg_title,@RequestParam String msg_content,@RequestParam Integer userId,
                                                        @RequestParam(required = false) MultipartFile msg_pic,@RequestParam Double lng,@RequestParam Double lat,@RequestParam String schoolNum,@RequestParam String address,@RequestParam(required = false) Double width,@RequestParam(required = false) Double height) throws IOException {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询所有留言根据时间倒序排列
        List<LeaveMessage> leaveMessageList = leaveMessageMapper.queryLeaveMsg(schoolNum);
//        //查询所有用户
//        List<User> userList = userMapper.queryAllUser();
        //非空判断
        if(msg_title == null || "".equals(msg_title)){
            return new BooleanResult(false,"留言标题不能为空!");
        }
        if(msg_content == null || "".equals(msg_content)){
            return new BooleanResult(false,"留言内容不能为空!");
        }
        //组装留言数据
        LeaveMessage leaveMessage = new LeaveMessage();
        leaveMessage.setMsg_title(msg_title);
        leaveMessage.setMsg_content(msg_content);
        leaveMessage.setSchoolNum(schoolNum);
        if (msg_pic != null && msg_pic.getSize() > 0) {
            String fileName = StringUtils.isBlank(genFileName(msg_pic)) ? "": genFileName(msg_pic);
            FileCopyUtils.copy(msg_pic.getBytes(), new File(genFilePath(fileName)));
            leaveMessage.setMsg_pic(fileName);
        }else {
            leaveMessage.setMsg_pic("");
        }
        if(userId != null || "".equals(userId)){
            leaveMessage.setUserId(userId);
        }else {
            leaveMessage.setUserId(0);
        }
        leaveMessage.setCreatetime(sdf.format(date));
        leaveMessage.setStatus("显示");
        leaveMessage.setLng(lng);
        leaveMessage.setLat(lat);
        leaveMessage.setAddress(address);
        leaveMessage.setWidth(width);
        leaveMessage.setHeight(height);
        //创建经纬度计算方法实例
        UploadTool uploadTool = new UploadTool();
        BooleanResult contents = uploadTool.uploadLeaveMessageLocation(lng,lat,leaveMessageList);//调用经纬度计算距离方法
        JSONArray list = JSON.parseArray(contents.getResultMap().get("distanceLessThan2").toString());//取到小于两公里内的用户集合
        int length = 0;
        for(Object obj : list){
            JSONObject json = JSONObject.parseObject(obj.toString());
            int user_id = Integer.parseInt(json.get("id").toString());//用户id
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            Calendar cal1 = Calendar.getInstance();
            cal1.add(Calendar.DAY_OF_MONTH, 0);
            String today = sdf1.format(cal1.getTime());//当前时间例：2015-05-21 00:00:00
            Calendar cal2 = Calendar.getInstance();
            cal2.add(Calendar.DAY_OF_MONTH,1);
            String tomorrow = sdf1.format(cal2.getTime());//明天 2015-05-22 00:00:00
            List<LeaveMessage> leaveMsg = leaveMessageMapper.queryLeaveMsgByUserId(user_id,today,tomorrow);//通过用户id,时间范围查询他们发布的留言
            length += leaveMsg.size();//留言总数
        }
//            if(length <= 10){//当天留言数量是否小于10条
                //结果判断
            User user = userMapper.queryUserByUserId(userId);
            if(user != null){
                Double money = user.getBalance();
                if(money >= 1.0){
                    int result = leaveMessageMapper.addLeaveMsg(leaveMessage);
                    if(result > 0){
                        //计费
                        Double balance = money - 1.0;
                        userMapper.updateBalance(balance,userId);
                        return new BooleanResult(true,"留言发布成功!");
                    }else {
                        return new BooleanResult(false,"留言发布失败!");
                    }
                }else {
                    return new BooleanResult(false,"余额不足，请充值");
                }

            }else {
                return new BooleanResult(false,"用户不存在");
            }

//            }else {
//                return new BooleanResult(false,"留言发布已超过10条!");
//            }

    }


    /**
     * 留言列表
     * @param lng 用户经度
     * @param lat 用户纬度
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/leaveMsgList")
    public @ResponseBody
    BooleanResult leaveMsgList(@RequestParam Double lng,@RequestParam Double lat,@RequestParam String schoolNum,@RequestParam Integer pageNo,@RequestParam Integer pageSize){

        if (pageNo == null) {
            pageNo = 1;// 起始页
        } else if (pageNo <= 0) {
            pageNo = 1;
        }
        int totalCount = leaveMessageMapper.totalMsgCount(schoolNum);
        int count = totalCount / pageSize;
        if(totalCount % pageSize > 0){
            count++;
        }
        if(pageNo >= count && count != 0){
            pageNo = count;
        }
        int startIndex = PaginationUtils.getStartIndex(pageNo,pageSize);


        //查询所有留言根据时间倒序排列
        List<LeaveMessage> leaveMessageList = leaveMessageMapper.queryLeaveMsgByPage(schoolNum,startIndex,pageSize);
        //查询所有用户
        List<User> userList = userMapper.queryAllUser();
        //查询所有留言评论
        List<Reply> replyList = replyMapper.queryAllReply();
        List listLm = new ArrayList();
        if(leaveMessageList != null && leaveMessageList.size() > 0){
            for(int i=0;i<leaveMessageList.size();i++){
                //新建留言实例
                LeaveMessage leaveMessage = new LeaveMessage();

                BigDecimal lngFirst=new BigDecimal(Double.toString(lng));
                Double lngLocation=lngFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位经度
                BigDecimal latFirst=new BigDecimal(Double.toString(lat));
                Double latLocation=latFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位纬度

                Double leLng = leaveMessageList.get(i).getLng();
                Double leLat = leaveMessageList.get(i).getLat();

                Double a = rad(lngLocation) - rad(leLng);
                Double b = rad(latLocation) - rad(leLat);
                Double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad(lat)) * Math.cos(rad(leLat)) * Math.pow(Math.sin(b / 2), 2)));
                s = s * EARTH_RADIUS;
                if(s<5.0){
                    //留言信息
                    leaveMessage.setId(leaveMessageList.get(i).getId());
                    leaveMessage.setMsg_title(leaveMessageList.get(i).getMsg_title());
                    leaveMessage.setMsg_content(leaveMessageList.get(i).getMsg_content());
                    leaveMessage.setUserId(leaveMessageList.get(i).getUserId());
                    leaveMessage.setMsg_pic("");
                    leaveMessage.setCreatetime("");
                    leaveMessage.setTotaluserId("");
                    leaveMessage.setIndexPage(0);
                    leaveMessage.setPageSize(0);
                    leaveMessage.setLng(leaveMessageList.get(i).getLng());
                    leaveMessage.setLat(leaveMessageList.get(i).getLat());

                    for(int j=0;j<userList.size();j++){
                        if(userList.get(j).getId() == leaveMessageList.get(i).getUserId()){
                            //用户的信息(名字,距离)
                            User userMsg = new User();
                            userMsg.setId(userList.get(j).getId());
                            userMsg.setUsername(userList.get(j).getUsername());
                            userMsg.setPhoneNum("");
                            userMsg.setCreatetime("");
                            userMsg.setGender("");
                            userMsg.setAddress("");
                            userMsg.setLoginPassword("");
                            userMsg.setLat(userList.get(j).getLat());
                            userMsg.setLng(userList.get(j).getLng());
                            userMsg.setUserpic("");

                            UploadTool uploadTool = new UploadTool();
                            BooleanResult contents = uploadTool.uploadLeaveMessageLocation(lng, lat,leaveMessageList);
                            JSONArray list = JSON.parseArray(contents.getResultMap().get("distanceAllList").toString());//取到用户与所有留言的距离
                            for(Object obj: list){
                                JSONObject json = JSONObject.parseObject(obj.toString());
                                int userId = Integer.parseInt(json.get("id").toString());
                                if(userId == leaveMessageList.get(i).getUserId()){
                                    userMsg.setDistance(Double.parseDouble(json.get("distance").toString()));
                                }
                            }
                            leaveMessage.getUserList().add(userMsg);
                        }
                    }
                    //回复数
                    for(int x=0;x<replyList.size();x++){
                        if(leaveMessageList.get(i).getId() == replyList.get(x).getLeaveMessageId() ){
                            //查询所有回复
                            int replyCount = replyMapper.queryReplyCount(leaveMessageList.get(i).getId());
                            leaveMessage.setReplyNum(replyCount);//回复数
                        }
                    }
                    listLm.add(leaveMessage);
                }
            }
        }
        BooleanResult booleanResult = new BooleanResult(true, "留言首页信息");
        booleanResult.getResultMap().put("listLm", listLm);
        return booleanResult;
    }


    /**
     * 留言详情
     * @param leaveMessageId 留言id
     * @param userId 阅读人id
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/leaveMsgDetails")
    public @ResponseBody
    BooleanResult leaveMsgDetails(@RequestParam Integer leaveMessageId,@RequestParam Integer userId,@RequestParam Double lng,@RequestParam Double lat){
        List msgDetailList = new ArrayList();//留言详情集合
        //根据留言id查询该留言详情
        LeaveMessage leaveMessage = leaveMessageMapper.queryLeaveMsgByLeaveMessageId(leaveMessageId);
        String totalUserId = leaveMessage.getTotaluserId();//已存在的阅读人id

        LeaveMessage leaveMsg = new LeaveMessage();//新建留言实例,存放留言数据
        //留言部分数据
        leaveMsg.setId(leaveMessage.getId());
        leaveMsg.setMsg_title(leaveMessage.getMsg_title());
        leaveMsg.setMsg_content(leaveMessage.getMsg_content());
        leaveMsg.setMsg_pic(leaveMessage.getMsg_pic());
        leaveMsg.setTotaluserId("");
        leaveMsg.setCreatetime("");
        leaveMsg.setLng(leaveMessage.getLng());
        leaveMsg.setLat(leaveMessage.getLat());
        leaveMsg.setHeight(leaveMessage.getHeight());
        leaveMsg.setWidth(leaveMessage.getWidth());
        leaveMsg.setAddress(leaveMessage.getAddress());
        if(totalUserId == null || "".equals(totalUserId)){//没有阅读人则直接添加阅读人id
            leaveMessageMapper.updateTotalUserId(leaveMessageId, userId); //用户阅读留言,插入用户id，记录阅读数
        }else {
            String[] arr = totalUserId.split(",");//阅读人id数组
            leaveMsg.setReadCount(arr.length);//阅读数
            if(!Arrays.asList(arr).contains(userId.toString())){//判断是否已存在阅读人的id
                leaveMessageMapper.updateTotalUserId(leaveMessageId, userId); //用户阅读留言,插入用户id，记录阅读数
            }
        }
        //msgDetailList.add(leaveMsg);//
        //用户部分数据
        int user_id = leaveMessage.getUserId();//发布留言人id
        User user = userMapper.queryUserByUserId(user_id);//根据发布留言人id查询该用户信息
        User userMsg = new User();//新建用户实例，存放用户数据
        userMsg.setId(user.getId());
        userMsg.setUsername(user.getUsername());
        if(user.getUserpic() != null){
            userMsg.setUserpic(user.getUserpic());
        }else {
            userMsg.setUserpic("");
        }
        if(user.getAddress() != null){
            userMsg.setAddress(user.getAddress());
        }else {
            userMsg.setAddress("");
        }
        userMsg.setLng(0.0);
        userMsg.setLat(0.0);
        userMsg.setCreatetime("");
        userMsg.setLoginPassword("");
        userMsg.setGender("");
        userMsg.setPhoneNum("");
        userMsg.setIndexPage(0);
        userMsg.setPageSize(0);
        if(user.getBalance() != null){
            userMsg.setBalance(user.getBalance());
        }else {
            userMsg.setBalance(0.0);
        }
        Double userLng = leaveMessage.getLng();//信息的经度
        Double userLat = leaveMessage.getLat();//信息的纬度
        //阅读留言用户的经纬度，截取后六位
        BigDecimal lngFirst=new BigDecimal(Double.toString(lng));
        Double lngLocation=lngFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位经度
        BigDecimal latFirst=new BigDecimal(Double.toString(lat));
        Double latLocation=latFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位纬度
        //计算发布留言人与阅读人的距离
        Double a = rad(lngLocation) - rad(userLng);
        Double b = rad(latLocation) - rad(userLat);
        Double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad(lat)) * Math.cos(rad(userLat)) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        userMsg.setDistance(s);//距离
        leaveMsg.getUserList().add(userMsg);//---------------把用户数据放入留言实例
        //评论,回复部分数据
        //根据留言id查询对应该留言的评论回复信息
        List<Reply> replyList = replyMapper.queryReplyByLeaveMessageId(leaveMessageId);
        if(replyList != null && replyList.size()>0){
            for(int i=0;i<replyList.size();i++){
                int commentId = replyList.get(i).getUserId();//评论人的id
                int tagetUserId = replyList.get(i).getTargetUserId();//回复评论的人的id
                String content = replyList.get(i).getReplyContent();//评论内容(回复内容)
                String time = replyList.get(i).getCreatetime();//评论时间
                int leaveMegId = replyList.get(i).getLeaveMessageId();//留言id
                int replyId = replyList.get(i).getId();//评论id
                int advertiseId = replyList.get(i).getAdvertiseId();
                Reply reply = new Reply();
                //通过评论人id查询评论人的相关信息
                User commentUser = userMapper.queryUserByUserId(commentId);//发布评论的人的信息
                User targetUser = userMapper.queryUserByUserId(tagetUserId);//回复评论的人的信息 tagetUserId !=0才有回复评论人的信息
                reply.setId(replyId);//评论id
                reply.setUserId(commentUser.getId());//评论人id
                reply.setUserName(commentUser.getUsername());//评论人的名字
                if(commentUser.getUserpic() != null){
                    reply.setUserPic(commentUser.getUserpic());//评论人的头像
                }else {
                    reply.setUserPic("");//评论人的头像
                }
                if(leaveMegId != 0){
                    reply.setAdvertiseId(0);
                }else {
                    reply.setAdvertiseId(advertiseId);
                }
                reply.setReplyContent(content);//评论内容
                reply.setLeaveMessageId(leaveMegId);
                reply.setCreatetime(time);//评论时间
                if(targetUser != null){
                    reply.setTargetUserId(targetUser.getId());//回复评论的人的id
                }else {
                    reply.setTargetUserId(0);
                }
                if(targetUser != null){//当tagetUserId=0，进行非空判断
                    reply.setTargetName(targetUser.getUsername());//回复评论的人的名字
                }else {
                    reply.setTargetName("");
                }
                leaveMsg.getReplyList().add(reply);//-----------------把评论回复数据放入留言实例
            }
        }
        msgDetailList.add(leaveMsg);//---------------把留言实例放入集合
        BooleanResult booleanResult = new BooleanResult(true,"留言详情");
        booleanResult.getResultMap().put("msgDetailList",msgDetailList);
        return booleanResult;
    }


    /**
     * 点击地图查询周边留言
     * @param lng
     * @param lat
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/searchOtherLeaveMsg")
    public @ResponseBody BooleanResult searchOtherLeaveMsg(@RequestParam Double lng,@RequestParam Double lat){
        BigDecimal lngFirst=new BigDecimal(Double.toString(lng));
        Double lngLocation=lngFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位经度
        BigDecimal latFirst=new BigDecimal(Double.toString(lat));
        Double latLocation=latFirst.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();//取后六位纬度
        List<LeaveMessage> leaveMessageList = leaveMessageMapper.queryAllLeaveMsg();
        Double msgLng = 0.0;
        Double msgLat = 0.0;
        List listLm = new ArrayList();

        if(leaveMessageList!= null &&leaveMessageList.size() > 0){
            for(int i=0;i<leaveMessageList.size();i++){
                LeaveMessage leaveMessage = new LeaveMessage();
                SimpleDateFormat  df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                long day= 0;
                long hour= 0;
                long min= 0;
                try {
                    Date d1 = df.parse(df.format(date));
                    Date d2 = df.parse(leaveMessageList.get(i).getCreatetime());
                    long l=d1.getTime()-d2.getTime();
                     day=l/(24*60*60*1000);
                     hour=(l/(60*60*1000)-day*24);
                     min=((l/(60*1000))-day*24*60-hour*60);
                } catch (Exception e){

                }
                msgLng = leaveMessageList.get(i).getLng();
                msgLat = leaveMessageList.get(i).getLat();
                Double a = rad(lngLocation) - rad(msgLng);
                Double b = rad(latLocation) - rad(msgLat);
                Double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad(lat)) * Math.cos(rad(msgLat)) * Math.pow(Math.sin(b / 2), 2)));
                s = s*EARTH_RADIUS;
                s = Math.round(s * 10000.0) / 10000.0;
                if(s<10.0 && min < 15 && day == 0 && hour == 0){
                    leaveMessage.setId(leaveMessageList.get(i).getId());
                    leaveMessage.setMsg_title("");
                    leaveMessage.setMsg_content("");
                    leaveMessage.setMsg_pic("");
                    leaveMessage.setTotaluserId("");
                    leaveMessage.setCreatetime("");
                    leaveMessage.setStatus("");
                    leaveMessage.setSchoolNum("");
                    leaveMessage.setAddress("");
                    leaveMessage.setWidth(0.0);
                    leaveMessage.setHeight(0.0);
                    leaveMessage.setLng(leaveMessageList.get(i).getLng());
                    leaveMessage.setLat(leaveMessageList.get(i).getLat());
                    leaveMessage.setUserId(leaveMessageList.get(i).getUserId());
                    listLm.add(leaveMessage);
                }
            }

            BooleanResult booleanResult = new BooleanResult(true,"周边留言坐标");
            booleanResult.getResultMap().put("listLm",listLm);
            return booleanResult;
        }else {
            return new BooleanResult(false,"没有留言信息");
        }
    }



    private String genFilePath(String fileName) {
        return ApplicationParams.IMG_SAVE_FOLDER + fileName;
    }

    private String genFileName(MultipartFile file) {
        // 使用时间做文件的prefix，防止文件冲突;
        String prefix = String.valueOf(new Date().getTime());
        return prefix + "-" + UUID.randomUUID();
    }

    //计算地图上两点距离辅助方法
    private static final double EARTH_RADIUS = 6378.137;// 赤道半径(单位m)

    /**
     * 转化为弧度(rad)
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }


    /**
     * 以下是后台使用方法
     */
    //查询留言总数
    public int totalCount(){
        return leaveMessageMapper.totalCount();
    }

    //分页查询所有留言
    public List<LeaveMessage> queryAllMsg(Integer indexPage,Integer pageSize){
        return leaveMessageMapper.queryAllMsg(indexPage,pageSize);
    }

    //根据条件查询总数
    public int totalCountByCondition(LeaveMessage leaveMessage){
        return leaveMessageMapper.totalCountByCondition(leaveMessage);
    }

    //根据条件查询 留言
    public List<LeaveMessage> queryAllMsgByCondition(LeaveMessage leaveMessage){
        return leaveMessageMapper.queryAllMsgByCondition(leaveMessage);
    }

    //更新显示状态
    public int updateStatus(Integer id,String status){
        return leaveMessageMapper.updateStatus(id,status);
    }

}